package com.kkd.kkdapp.activity;

import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.KkdAppInfo;
import com.kkd.kkdapp.gesture.GestureContentView;
import com.kkd.kkdapp.gesture.GestureDrawline.GestureCallBack;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.view.KKdDialog;
import com.kkd.kkdapp.view.RoundImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 手势绘制/校验界面
 * 
 */
public class GestureVerifyActivity extends Activity implements
		android.view.View.OnClickListener {
	/** 手机号码 */
	public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";
	/** 意图 */
	public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";

	private FrameLayout gesture_container;
	private GestureContentView mGestureContentView;
	private TextView pl_message_text;
	protected SystemBarTintManager mTintManager;
	private Button leftButton, rightButton;
	private int numFailedAttempts = 0;
	private boolean update;
	private RoundImageView pattern_head;
	private RelativeLayout top_layout;
	private RelativeLayout text_title;
	private KKdDialog mPopupWindow;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = this.getIntent();
		update = intent.getBooleanExtra("update", false);
		setContentView(R.layout.activity_gesture_verify);
		user_name = (TextView) findViewById(R.id.user_name);
		top_layout = (RelativeLayout) this.findViewById(R.id.top_layout);
		text_title = (RelativeLayout) this.findViewById(R.id.text_title);
		BaseApplication.getInstance().addGestureActivity(this);
		initTintManager();
		setUpViews();
		setUpListeners();
		if (update) {
			leftButton.setVisibility(View.GONE);
			rightButton.setVisibility(View.GONE);
			pl_message_text.setText("请输入原来的密码");
			user_name.setVisibility(View.GONE);
			top_layout.setVisibility(View.VISIBLE);
		} else {
			leftButton.setVisibility(View.VISIBLE);
			rightButton.setVisibility(View.VISIBLE);
			user_name.setVisibility(View.VISIBLE);
			top_layout.setVisibility(View.GONE);
		}
		initTextView();
	}

	/**
	 * 初始化为状态栏为纯黑色
	 */
	private void initTintManager() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}

		mTintManager = new SystemBarTintManager(this);
		mTintManager.setStatusBarTintEnabled(true);
		mTintManager.setNavigationBarTintEnabled(true);
		mTintManager.setStatusBarTintResource(R.color.transparent);
		// mTintManager.setTintColor(0x05FF0000);
	}

	@TargetApi(19)
	public void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	private void setUpViews() {

		gesture_container = (FrameLayout) findViewById(R.id.gesture_container);
		pl_message_text = (TextView) findViewById(R.id.pl_message_text);
		leftButton = (Button) this.findViewById(R.id.pl_left_button);
		rightButton = (Button) this.findViewById(R.id.pl_right_button);
		pattern_head = (RoundImageView) this.findViewById(R.id.pattern_head);
		pattern_head.setVisibility(View.VISIBLE);
		ImageLoader.getInstance().displayImage(
				PreferenceUtils.getInstance().getHeadUrl(this), pattern_head);
		if (CurUserModel.getCurUser() != null) {

			if (!TextUtils.isEmpty(CurUserModel.getCurUser().realName)) {
				user_name.setVisibility(View.VISIBLE);
				user_name.setText(CurUserModel.getCurUser().realName
						+ " , 欢迎您 ");
			} else if (!TextUtils.isEmpty(CurUserModel.getCurUser().mobile)) {
				user_name.setVisibility(View.VISIBLE);
				user_name.setText(CurUserModel.getCurUser().mobile + " , 欢迎您 ");
			}

		} else {
			user_name.setVisibility(View.GONE);
		}
		//
		// 初始化一个显示各个点的viewGroup
		mGestureContentView = new GestureContentView(this, true,
				PreferenceUtils.getInstance().getGesturePW(this),
				new GestureCallBack() {

					@Override
					public void onGestureCodeInput(String inputCode) {

					}

					@Override
					public void checkedSuccess() {
						mGestureContentView.clearDrawlineState(0L);
						KkdAppInfo appinfo = new KkdAppInfo();
						appinfo.backgroundTime = System.currentTimeMillis() / 1000;
						KkdAppInfo.insert(appinfo);
						if (update) {
							Intent intent = new Intent(
									GestureVerifyActivity.this,
									GestureEditActivity.class);
							intent.putExtra("update", update);
							startActivity(intent);
							GestureVerifyActivity.this.finish();
						} else {

							GestureVerifyActivity.this.finish();

						}
					}

					@Override
					public void checkedFail() {
						mGestureContentView.clearDrawlineState(0L);
						++numFailedAttempts;
						if (numFailedAttempts < 5) {
							String msg = "密码错误，还可以再输入"
									+ (5 - numFailedAttempts) + "次";
							pl_message_text.setText(msg);
							pl_message_text.setTextColor(Color.RED);
						} else {
							onForgotPassword();
						}
						// 左右移动动画
						Animation shakeAnimation = AnimationUtils
								.loadAnimation(GestureVerifyActivity.this,
										R.anim.shake);
						pl_message_text.startAnimation(shakeAnimation);
					}

					@Override
					public void position(String position) {
						// TODO Auto-generated method stub

					}
				});
		// 设置手势解锁显示到哪个布局里面
		mGestureContentView.setParentView(gesture_container);
	}

	private void setUpListeners() {
		leftButton.setOnClickListener(this);
		rightButton.setOnClickListener(this);
		text_title.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.pl_left_button:
			showPupopWidow(leftButton);
			break;
		case R.id.pl_right_button:
			onForgotPassword();
			break;
		case R.id.text_title: // 返回
			finish();
			break;
		default:
			break;
		}
	}

	public void showPupopWidow(View v) {
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.password_pupopwindow, null);

		mPopupWindow = new KKdDialog(this, R.style.TransparentDialog);
		mPopupWindow.setContentView(layout);
		mPopupWindow.setCanceledOnTouchOutside(true);
		mPopupWindow.show();
		// final PopupWindow mPopupWindow = new PopupWindow(layout,
		// WindowManager.LayoutParams.FILL_PARENT,
		// WindowManager.LayoutParams.FILL_PARENT, true);
		// mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// mPopupWindow.setOutsideTouchable(true);
		// mPopupWindow
		// .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		//
		// mPopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
		LinearLayout popupwidow_ll = (LinearLayout) layout
				.findViewById(R.id.popupwidow_ll);
		if (mPopupWindow.isShowing()) {
			Animation animation = AnimationUtils.loadAnimation(this,
					R.anim.openparticulars_translate);
			popupwidow_ll.setAnimation(animation);
		} else {

			Animation animation = AnimationUtils.loadAnimation(this,
					R.anim.openparticulars_translate);
			popupwidow_ll.setAnimation(animation);
		}
		Button close = (Button) layout.findViewById(R.id.close); // 取消
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
			}
		});
		Button login = (Button) layout.findViewById(R.id.login); // 重新登录
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				PreferenceUtils.getInstance().clearSharedPreferences(
						GestureVerifyActivity.this);
				Intent intent = new Intent(GestureVerifyActivity.this,
						LoginActivity.class);
				intent.putExtra("gesture", true);
				startActivity(intent);
				finish();
				mPopupWindow.dismiss();
			}
		});

	}

	protected void onForgotPassword() {

		PreferenceUtils.getInstance().clearSharedPreferences(this);
		Intent intent = new Intent(this, LoginActivity.class);
		intent.putExtra("gesture", true);
		startActivity(intent);
		setResult(400);
		finish();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mGestureContentView.reCycle();
	}

	private TextView textView;
	private TextView user_name;
	private long mExitTime;

	private void initTextView() {
		textView = new TextView(this);
		textView.setBackgroundResource(R.drawable.bg_back_toast);
		textView.setText(R.string.homeactivity_exit);
		textView.setGravity(Gravity.CENTER);
		textView.setTextSize(16);
		textView.setTextColor(Color.parseColor("#333333"));
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (!update) {
				if ((System.currentTimeMillis() - mExitTime) > 2000) {
					// AppUtil.makeToastForCustomer(GestureVerifyActivity.this,
					// "再按一次退出程序");
					Toast toast = new Toast(GestureVerifyActivity.this);
					toast.setDuration(Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.BOTTOM, 0, 0);
					toast.setView(textView);
					toast.show();
					mExitTime = System.currentTimeMillis();
				} else {
					// 必须退出整个程序
					finish();
					BaseActivity.isNeedUpdateTime = false;
					BaseApplication.getInstance().exitGestureActivity();
					BaseApplication.getInstance().exitKkd();// 退出app
				}
			} else {
				finish();
			}

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
